package sk.stuba.fiit.team14.game.mapengine;

import java.util.LinkedList;

public class Map {
	private final LinkedList<Component> mTail = new LinkedList<Component>();
	
	public void addComponent(Component pComponent) {
		mTail.add(pComponent);
	}
	
	public void removeComponent(Component pComponent) {
		if (mTail.contains(pComponent)) {
			mTail.remove(pComponent);
		}
	}
	
	public void updateMap() {
		boolean updated = true;
		while (updated) {
			updated = false;
			for (int i=0; i < mTail.size(); i++) {
				if (mTail.get(i).isControllable) {
					updated |= updateCell(mTail.get(i), i);
				}
			}
		}
	}
	
	private boolean updateCell(Component pComponent, int pos) {
		if (!pComponent.wantMove()) return false;
		
		boolean canMove = true;
		boolean updated = false;
		
		for (int i=0; i < mTail.size(); i++) {
			if (pos == i) continue;
			
			if (mTail.get(i).isInSameCell(pComponent.getNextX(), pComponent.getNextY())) {
				if (mTail.get(i).isMovable && pComponent.isControllable) {
					mTail.get(i).move(pComponent.getDirection());
					updated = updateCell(mTail.get(i), i);
				}
				
				canMove = updated;
			}
		}
		
		if (canMove) {
			canMove = pComponent.setCell(pComponent.getNextX(), pComponent.getNextY());
		}
		
		pComponent.move(0);
		
		return canMove;
	}
}
